package com.hd.appcommon.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkworkflow_1_0.Client;
import com.aliyun.dingtalkworkflow_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.JsonArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.BiConsumer;

import static com.aliyun.teautil.Common.empty;

/**
 * 钉钉OA审批自有工作流，工具类
 */

@Slf4j
@Component
public class DDOAUtil {

    @Autowired
    DDUtils ddUtils;

    //学生课程替代申请
    public String ProcessCode_CourseReplace = "PROC-8290B220-0048-49EC-92C9-D171E7D07F14";
    public Long MicroappAgentId = 2642151985L;
//    public String ProcessCode_Test = "PROC-01DC4BDC-74A1-4B41-9CA7-0E6D47EDD766";

    public com.aliyun.dingtalkworkflow_1_0.Client createClient() throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkworkflow_1_0.Client(config);
    }

    //获取审批实例ID列表
    public JSONObject getProcessesInstanceIds(String processCode, Long startTime, Long endTime, Long maxResults, Long nextToken, List<String> userIds, List<String> statuses) throws Exception {
//        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsHeaders listProcessInstanceIdsHeaders =
                new ListProcessInstanceIdsHeaders();

        listProcessInstanceIdsHeaders.xAcsDingtalkAccessToken = ddUtils.getAccessToken();
        ListProcessInstanceIdsRequest listProcessInstanceIdsRequest =
                new ListProcessInstanceIdsRequest()
                        .setProcessCode(processCode)
                        .setStartTime(startTime)
                        .setMaxResults(maxResults)
                        .setNextToken(nextToken);

        if (endTime != null) {
            listProcessInstanceIdsRequest.setEndTime(endTime);
        }
        if (userIds != null) {
            listProcessInstanceIdsRequest.setUserIds(userIds);
        }
        if (statuses != null) {
            listProcessInstanceIdsRequest.setStatuses(statuses);
        }

        try {
            ListProcessInstanceIdsResponse res = client.listProcessInstanceIdsWithOptions(listProcessInstanceIdsRequest, listProcessInstanceIdsHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            return new JSONObject(res.getBody().getResult().toMap());
        } catch (TeaException err) {
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题

                System.out.println(err.data);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.data);
            }
        }
        log.error("请求 获取审批实例ID列表 出错，返回空值");
        return null;
    }

    //获取单个审批实例详情
    public JSONObject getProcessInstancesInfo(String processInstanceId) throws Exception {
//        ava.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        GetProcessInstanceHeaders getProcessInstanceHeaders =
                new GetProcessInstanceHeaders();
        getProcessInstanceHeaders.xAcsDingtalkAccessToken = ddUtils.getAccessToken();
        GetProcessInstanceRequest getProcessInstanceRequest =
                new GetProcessInstanceRequest()
                        .setProcessInstanceId(processInstanceId);
        try {
            GetProcessInstanceResponse res = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            return new JSONObject(res.getBody().getResult().toMap());
        } catch (TeaException err) {
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.data);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.data);
            }
        }
        log.error("请求 获取单个审批实例详情 出错，返回空值");
        return null;
    }


    public JSONObject apply(String ddid,Long deptId, String processCode, Map<String, Object> data) throws Exception {
//        java.util.List<String> args = java.util.Arrays.asList(args_);
        Client client = createClient();
        StartProcessInstanceHeaders startProcessInstanceHeaders = new StartProcessInstanceHeaders();
        startProcessInstanceHeaders.xAcsDingtalkAccessToken = ddUtils.getAccessToken();


        List<StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues> form = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {

            StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues formValues =
                    new StartProcessInstanceRequest.StartProcessInstanceRequestFormComponentValues()
                            .setName(entry.getKey());

            //根据object类型将数据添加到map
            if (entry.getValue() instanceof List ){
//                System.out.println(entry.getValue().toString());
                List<Map<String,Object>> detailList = (List<Map<String, Object>>) entry.getValue();
                System.out.println(detailList.toString());

                JSONArray arrayRow = new JSONArray();
                for (int i=0;i<detailList.size();i++) {
                    Map<String, Object> detailMap = detailList.get(i);
                    JSONArray arrayCol = new JSONArray();
                    for (Map.Entry<String, Object> entryDetail : detailMap.entrySet()) {
                        JSONObject item = new JSONObject();
                        item.put("name",entryDetail.getKey());
                        item.put("value",entryDetail.getValue());
                        arrayCol.add(item);
                    }
                    arrayRow.add(arrayCol);
                }
                formValues.setValue(arrayRow.toString());
            } else if (entry.getValue() instanceof String ) {
                formValues.setValue(String.valueOf(entry.getValue()));
            }else {
                System.out.println("未能识别数据类型");
            }

            form.add(formValues);
        }

        StartProcessInstanceRequest startProcessInstanceRequest = new StartProcessInstanceRequest()
                .setOriginatorUserId(ddid)
                .setProcessCode(processCode)
                .setDeptId(deptId)
                .setMicroappAgentId(MicroappAgentId)
                .setFormComponentValues(form);

        System.out.println(startProcessInstanceRequest.toMap());

        try {
            StartProcessInstanceResponse res = client.startProcessInstanceWithOptions(startProcessInstanceRequest, startProcessInstanceHeaders, new RuntimeOptions());
            return new JSONObject(res.getBody().toMap());
        } catch (TeaException err) {
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.data);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!empty(err.code) && !empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.data);
            }
        }


        return null;
    }


}
